package com.lyl.syt.service.impl;/**
 * @author Mr.Luo
 * @date 2022-05-26 15:25
 */

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.lyl.syt.common.result.Result;
import com.lyl.syt.enums.PaymentTypeEnum;
import com.lyl.syt.enums.RefundStatusEnum;
import com.lyl.syt.model.order.OrderInfo;
import com.lyl.syt.model.order.PaymentInfo;
import com.lyl.syt.model.order.RefundInfo;
import com.lyl.syt.service.OrderService;
import com.lyl.syt.service.PaymentInfoService;
import com.lyl.syt.service.RefundService;
import com.lyl.syt.service.WeixinPayService;
import com.lyl.syt.utils.ConstantPropertiesUtils;
import com.lyl.syt.utils.HttpClient;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.Luo
 * @date 2022-05-26 15:25
 * @desc
 */
@Service
@RequiredArgsConstructor
public class WeixinPayServiceImpl implements WeixinPayService {
    private final OrderService orderService;
    private final PaymentInfoService paymentInfoService;
    private final RedisTemplate redisTemplate;
    private final RefundService refundService;

    @Override
    public Map<String, Object> createNative(Long orderId) {
        //先判断redis中是否有待支付的订单信息
        Map<String,Object> payMap = (Map<String, Object>) redisTemplate.opsForValue().get(orderId.toString());
        if (payMap != null) {
            return payMap;
        }
        //根据订单id获取订单信息
        OrderInfo order = orderService.getById(orderId);
        //保存交易记录
        paymentInfoService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
        //获取微信支付二维码
        Map<String, String> resultMap = getWeixinQrCode(order);
        //4、封装返回结果集
        Map<String,Object> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("totalFee", order.getAmount());
        map.put("resultCode", resultMap.get("result_code"));
        map.put("codeUrl", resultMap.get("code_url"));
        if (resultMap.get("result_code") != null) {
            //微信支付二维码2小时过期，可采取2小时未支付取消订单
            redisTemplate.opsForValue().set(orderId.toString(), map, 1000, TimeUnit.MINUTES);
        }
        return map;
    }

    @Override
    public Result queryPayStatus(Long orderId, String payType) {
        OrderInfo order = orderService.getById(orderId);
        Map<String, String> resultMap = getWeixinQrCode(order);
        if (MapUtil.isEmpty(resultMap)) {//出错
            return Result.fail().message("支付出错");
        }
        if ("SUCCESS".equals(resultMap.get("return_code"))) {//如果成功
            //更改订单状态，处理支付结果
            String out_trade_no = resultMap.get("out_trade_no");
            paymentInfoService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }

    @Override
    public boolean refund(Long orderId) {
        try {
            PaymentInfo paymentInfoQuery = paymentInfoService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

            RefundInfo refundInfo = refundService.saveRefundInfo(paymentInfoQuery);
            if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            Map<String,String> paramMap = new HashMap<>(8);
            paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfoQuery.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfoQuery.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfoQuery.getOutTradeNo()); //商户退款单号
//       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
//       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundService.updateById(refundInfo);
                return true;
            }
            return false;
        }  catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取微信支付二维码
     * @param order 订单信息
     * @return
     */
    private Map<String, String> getWeixinQrCode(OrderInfo order) {
        try {
            //1、设置参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = DateUtil.format(order.getReserveDate(), "yyyy年MM月dd日") + "就诊"+ order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            paramMap = WXPayUtil.xmlToMap(xml);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            return paramMap;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }
}
